package com.fernfx.xingtan.contacts.presenter;

import android.text.TextUtils;

import com.fernfx.xingtan.R;
import com.fernfx.xingtan.common.base.BaseEntity;
import com.fernfx.xingtan.common.base.BaseView;
import com.fernfx.xingtan.common.network.IRequestCallback;
import com.fernfx.xingtan.common.network.entity.NetworkOKResult;
import com.fernfx.xingtan.contacts.contract.SubmitFriendsAskContract;
import com.fernfx.xingtan.contacts.entity.SubmitFriendsAskEntity;
import com.fernfx.xingtan.contacts.model.SubmitFriendsAskModel;
import com.fernfx.xingtan.utils.FastJsonUtil;
import com.fernfx.xingtan.utils.OtherUtil;
import com.fernfx.xingtan.utils.ToastUtil;

import java.util.Map;

/**
 * Created by admin on 2018/8/7.
 */

public class SubmitFriendsAskPresenter<P extends SubmitFriendsAskContract.View> implements SubmitFriendsAskContract.Presenter,IRequestCallback {
    private P P;
    private SubmitFriendsAskContract.Model model;

    @Override
    public void init(BaseView P) {
        this.P =(P)P;
        this.model = new SubmitFriendsAskModel();
    }

    @Override
    public void request(Map<String, Object> requestArgsMap) {
        P.getActivity().showLoading();
        model.request(requestArgsMap,this);
    }

    @Override
    public void detachView() {
        if (null != model) {
            model = null;
        }
    }

    @Override
    public void onSuccessful(NetworkOKResult result) {
        String message = result.getMessage();
        P.getActivity().hideLoading();
        if (TextUtils.isEmpty(message)) {
            onNetworkError(result.getMessage(),500);
            return;
        }

        SubmitFriendsAskEntity submitFriendsAskEntity= FastJsonUtil.fromBean(message,SubmitFriendsAskEntity.class);
        if (OtherUtil.checkRequestStatus(submitFriendsAskEntity.getSuccess(),submitFriendsAskEntity.getStatus())) {
            //提示
            ToastUtil.showCentertoast("发送成功");
            P.getActivity().finish();
        }else {
            ToastUtil.showCentertoast(submitFriendsAskEntity.getMsg());
        }
    }

    @Override
    public void onFailure(String errorMessage, int errorCode) {
        P.getActivity().hideLoading();
        if (TextUtils.isEmpty(errorMessage)) {
            onNetworkError(errorMessage,errorCode);
            return;
        }

        final BaseEntity baseEntity = FastJsonUtil.fromBean(errorMessage, BaseEntity.class);
        if (null != baseEntity && !TextUtils.isEmpty(baseEntity.getMsg())){
            ToastUtil.showCentertoast(baseEntity.getMsg());
        }
    }

    @Override
    public void onNetworkError(String errorMessage, int errorCode) {
        P.getActivity().hideLoading();
        ToastUtil.showCentertoast(R.string.network_error);
    }
}
